package com.esms.controller;

import com.esms.dao.DepartmentMapper;
import com.esms.dao.EmployeeMapper;
import com.esms.po.Department;
import com.esms.po.Employee;
import com.esms.po.WeekGrand;
import com.esms.po.WeekRecordInfoMent;
import com.esms.po.WeekTempGrand;
import com.esms.service.ILogService;
import com.esms.service.impl.EmployeeWeekServerImpl;
import com.esms.utils.DateUtil;
import com.esms.utils.Message;
import com.esms.vo.EmployeeWeekGrandVO;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.esms.controller.EmployeeWeekCheckController.Text2Html;

/**
 * @author : [ko]
 * @version : [v1.0]
 * @description : [员工周纪实Controller]
 * @createTime : [2022/2/27 09:23]
 * @updateUser : [ko]
 * @updateTime : [2022/2/27 09:23]
 * @updateRemark : [说明本次修改内容]
 */

@Controller
@RequestMapping("/empWeekInfo")
public class EmployeeWeekController {

	@Autowired
	private ILogService logService;

	@Autowired
	private EmployeeWeekServerImpl employeeWeekServerImpl;

	@Autowired
	private EmployeeMapper employeeMapper = null;

	@Autowired
	private DepartmentMapper departmentMapper = null;

	/**
	 * 查找周纪实信息
	 * 
	 * @param wFlag 根据类型
	 * @return
	 * @throws Exception
	 **/
	@RequestMapping("/findSelective.do")
	@ResponseBody
	public EmployeeWeekGrandVO findWeekInfo(@RequestParam(value = "page", defaultValue = "1") int pageNum,
			@RequestParam(value = "limit", defaultValue = "5") int limit,
			@RequestParam(value = "w_flag", defaultValue = "") String wFlag,
			@RequestParam(value = "w_finshLivel", defaultValue = "") String wFinshLivel, HttpSession httpSession)
			throws Exception {

		/**
		 * select e.e_account,e.e_name,d.d_name,d.d_id,q.q_targetscore from employee e
		 * left join department d on e.d_id = d.d_id left join q_assessment q on
		 * e.e_account = q.q_daccount and q.q_targetid = #{arg1} where e.d_id = #{arg0}
		 * and e.e_isdel='1' order by e.e_account;
		 **/

		int eId = (Integer) httpSession.getAttribute("employeeId");
		Employee employee = employeeMapper.selectByPrimaryKey(eId);
		String wAccount = employee.geteAccount();// 当前登录员工工号
		int wDId = employee.getdId();// 当前登录员工所在部门

		WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();

		wWeekMent.setwAccount(wAccount);
		wWeekMent.setwDId(wDId);
		wWeekMent.setwFlag(wFlag);
		wWeekMent.setwFinshLivel(wFinshLivel);

		List<WeekRecordInfoMent> weekInfoListNew = new ArrayList<WeekRecordInfoMent>();
		try {
			List<WeekRecordInfoMent> weekInfoList  = employeeWeekServerImpl.getEmpDeployeeWeekList(wWeekMent);
			for(WeekRecordInfoMent weekRecordInfoMent:weekInfoList){
				String weekInfo = weekRecordInfoMent.getwWeekInfo();
				String wTempOraryInfo = weekRecordInfoMent.getwTempOraryInfo();
				if(StringUtil.isNotEmpty(weekInfo)){
					weekRecordInfoMent.setwWeekInfo(Text2Html(weekInfo));//重要转换
				}
				if(StringUtil.isNotEmpty(wTempOraryInfo)){
					weekRecordInfoMent.setwTempOraryInfo(Text2Html(wTempOraryInfo));//重要转换
				}
				weekInfoListNew.add(weekRecordInfoMent);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 设置前台需要的数据
		EmployeeWeekGrandVO employeeWeekGrandVO = new EmployeeWeekGrandVO();
		employeeWeekGrandVO.setCode(0);
		employeeWeekGrandVO.setMsg("");
		employeeWeekGrandVO.setCount(weekInfoListNew.size());
		employeeWeekGrandVO.setData(weekInfoListNew);
		return employeeWeekGrandVO;
	}

	@RequestMapping("/addWeekInfo.do")
	@ResponseBody
	public Message addWeekInfo(@RequestParam("listWeek") String listWeek, @RequestParam("listTemp") String listTemp,
			HttpSession httpSession) throws Exception {
		int req = 0;
		String reMsg = "";
		ObjectMapper mapper = new ObjectMapper();
		// Date date = new Date();
		Timestamp date = new Timestamp(new Date().getTime());
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		// 当前登录员工信息
		Integer eId = (Integer) httpSession.getAttribute("employeeId");
		Employee employee = employeeMapper.selectByPrimaryKey(eId);
		int dId = employee.getdId();// 当前登录员工的部门ID
		String eAccount = employee.geteAccount();// 当前登录员工的工号
		String eName = employee.geteName();// 当前登录员工的姓名

		Department department = departmentMapper.selectByPrimaryKey(dId);

		String qCreateQuarter = DateUtil.GetQuarterByDate(formatter.format(currentTime));// 计算当前日期属于第几季度
		String qCreateWeek = DateUtil.getWeek(formatter.format(currentTime));// 计算当前日期属于哪年哪个月的第几周,例如：2022-2-5  2022年2月第5周

		//标题设置：第几月
		String weekMonYear = DateUtil.getMonthForNowDay(formatter.format(currentTime));
		//标题设置：本月第几周
		String weekMonth = DateUtil.getWeekForNowDay(formatter.format(currentTime));
		//标题设置：本月第几周开始时间-结尾之间(根据当前日期直接返回本周开始日期和结束日期)
		String weekFirLa = DateUtil.getFirstLastWeek(currentTime);//当前日期本周开始第一天：2022年03月07 - 2022年03月13

		String dName = department.getdName();//当前员工坐在部门名称

		try {

			//首先进来判断一个该员工是否在本周已经填写过周纪实，如果已经填写，不需要再次填写，修改原有的即可
			//根据工号、部门、现在时刻所在的本月的第几周，去查找
			WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();

			wWeekMent.setwAccount(eAccount);
			wWeekMent.setwDId(dId);
			wWeekMent.setwCreateWeek(qCreateWeek);

			List<WeekRecordInfoMent> weekInfoList = employeeWeekServerImpl.getEmpDeployeeWeekList(wWeekMent);
			if(weekInfoList.size()>0){

				return Message.error("本周的周纪实已填写,直接修改即可");
			}

			//周计划
			JavaType weekJt = mapper.getTypeFactory().constructParametricType(ArrayList.class, WeekGrand.class);
			List<WeekGrand> listWeekGrand = (List<WeekGrand>) mapper.readValue(listWeek, weekJt);
			//临时任务
			JavaType weekTempJt = mapper.getTypeFactory().constructParametricType(ArrayList.class, WeekTempGrand.class);
			List<WeekTempGrand> listTempGrand = (List<WeekTempGrand>) mapper.readValue(listTemp, weekTempJt);

			// 就是2022年2月份第五周

			String weekInfo ="";//周计划
			String tempOraryInfo = "";//临时任务
			//获取周计划
			for (int i = 0; i < listWeekGrand.size(); i++) {
				WeekGrand weekGrandData = listWeekGrand.get(i);
				weekInfo = weekGrandData.getWeekInfo();// 周计划内容
			}

			//获取临时任务
			for (int i = 0; i < listTempGrand.size(); i++) {
				WeekTempGrand weekGrandData = listTempGrand.get(i);
				tempOraryInfo = weekGrandData.getTempOraryInfo();// 临时任务内容
			}

			wWeekMent.setwId(null);
			wWeekMent.setwAccount(eAccount);// 工号
			wWeekMent.setwName(eName);//姓名
			wWeekMent.setwDId(dId);// 部门
			wWeekMent.setwDname(dName);
			wWeekMent.setwWeekNum(1);// 周计划序列
			wWeekMent.setwFlag("1");// 周计划标识
			wWeekMent.setwWeekInfo(weekInfo);// 周计划内容
			wWeekMent.setwTempOraryInfo(tempOraryInfo);// 弃用，和周计划公用一个就可以了
			wWeekMent.setwFinshLivel("0");// 周计划完成情况
			wWeekMent.setwCheckStatus("0");// 领导审核状态
			wWeekMent.setwCheckResult("");// 审核意见内容
			wWeekMent.setwCreateTime(date);// 操作时间
			wWeekMent.setwUpdateTime(date);
			wWeekMent.setwCreateQuarter(qCreateQuarter);
			wWeekMent.setwCreateWeek(qCreateWeek);
			wWeekMent.setwWeekMonYear(weekMonYear);
			wWeekMent.setwWeekMonth(weekMonth);
			wWeekMent.setwWeekFirLa(weekFirLa);
			wWeekMent.setwWeekScore(0);
			wWeekMent.setwWeekScoreSum(0);
			wWeekMent.setwWeekScoreCalu(0);
			wWeekMent.setwByzd("");
			wWeekMent.setwByzd1("");
			wWeekMent.setwByzd2("");

			req = employeeWeekServerImpl.insertWeekInfo(wWeekMent);

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (req < 0) {
			return Message.fail();
		} else {
			logService.addLog(this.getClass().getName(),Thread.currentThread().getStackTrace()[1].getMethodName(),(Integer)httpSession.getAttribute("employeeId"),
					"周纪实提交成功");
			return Message.success("周纪实提交成功");
		}
	}

	/**
	 * 根据主键删除周纪实信息(需要注意一点：就是已经审核过的，是不允许删除和修改的，只能查看,其实就是结果查询)
	 * 
	 * @param wId
	 * @throws Exception
	 */
	@RequestMapping("/deleteByPrimaryKey.do")
	@ResponseBody
	public Message deleteByPrimaryKey(int wId) throws Exception {
		int req = 0;

		WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();
		wWeekMent.setwId(wId);
		try {
			req = employeeWeekServerImpl.deleteByPrimaryKey(wWeekMent);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (req < 0) {
			return Message.fail();
		} else {
			return Message.success();
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 */
	@RequestMapping("/deleteByQuery.do")
	@ResponseBody
	public Message deleteByQuery(@RequestParam(value = "arr") int[] ids) {
		int req = 0;
		// 如果有id才执行
		WeekRecordInfoMent wWeekMent = new WeekRecordInfoMent();
		if (ids.length > 0) {
			for (int i : ids) {
				wWeekMent.setwId(i);
				req = employeeWeekServerImpl.deleteByPrimaryKey(wWeekMent);
			}
		}
		return Message.success("删除成功");

	}

	/**
	 * 根据id查询员工
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/selectVoByPrimaryKey.do")
	@ResponseBody
	public WeekRecordInfoMent selectVoByPrimaryKey(int id) {
		WeekRecordInfoMent weekRecordInfoMent = new WeekRecordInfoMent();
		try {
			weekRecordInfoMent = employeeWeekServerImpl.selectVoByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return weekRecordInfoMent;
	}

	/**
	 * 编辑周纪实信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/editWeekInfo.do")
	@ResponseBody
	public Message editWeekInfo(WeekRecordInfoMent weekRecordInfoMent) throws Exception {

		// Date date = new Date();
		Timestamp date = new Timestamp(new Date().getTime());
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		String qCreateQuarter = DateUtil.GetQuarterByDate(formatter.format(currentTime));// 计算当前日期属于第几季度
		String qCreateWeek = DateUtil.getWeek(formatter.format(currentTime));// 计算当前日期属于哪年哪个月的第几周,例如：2022-2-5

		if (StringUtils.isEmpty(weekRecordInfoMent.getwWeekInfo())) {
			return Message.error("请填写内容");
		}

		String wWeekInfo = weekRecordInfoMent.getwWeekInfo();//周计划
		String wTempOraryInfo = weekRecordInfoMent.getwTempOraryInfo();//临时任务

		// 重新设置修改时间
		weekRecordInfoMent.setwUpdateTime(date);
		weekRecordInfoMent.setwCreateQuarter(qCreateQuarter);
		weekRecordInfoMent.setwCreateWeek(qCreateWeek);
		if(StringUtil.isNotEmpty(wWeekInfo)){
			weekRecordInfoMent.setwWeekInfo(wWeekInfo);
		}
		if(StringUtil.isNotEmpty(wTempOraryInfo)){
			weekRecordInfoMent.setwTempOraryInfo(wTempOraryInfo);
		}


		employeeWeekServerImpl.updateByPrimaryKeySelective(weekRecordInfoMent);
		return Message.success("编辑成功");
	}

}
